package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.util.Consts;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

   @Autowired
   private StringRedisTemplate template ;
    @Override
    public void saveCode(String phone, String code) {
        template.opsForValue().set(RedisKeys.VERIFY_CODE.join(phone),code ,RedisKeys.VERIFY_CODE.getTime(),TimeUnit.SECONDS );
    }

    @Override
    public String getCode(String phone) {
        String key =RedisKeys.VERIFY_CODE.join(phone);
        String code = template.opsForValue().get(key);
        return code;
    }

    @Override
    public String saveToken(UserInfo user) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        String userStr = JSON.toJSONString(user);
        template.opsForValue().set(key,userStr ,RedisKeys.USER_LOGIN_TOKEN.getTime() ,TimeUnit.SECONDS );
        return token;
    }

    @Override
    public UserInfo getUserByToken(String token) {
        if(!StringUtils.hasLength(token)){
            return null ;
        }
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        System.out.println(key);
        if(template.hasKey(key)) {
            String userStr = template.opsForValue().get(key);
            UserInfo userInfo = JSON.parseObject(userStr, UserInfo.class);
            template.expire(key, RedisKeys.USER_LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
            return userInfo;
        }
        return null;

    }


    @Override
    public void setPassword(String nickname, String password) {
        template.opsForValue().set(nickname,password,Consts.VERIFY_CODE_VAI_TIME*60,TimeUnit.SECONDS);
    }

    @Override
    public String getPassword(String nickname) {
        return template.opsForValue().get(nickname);
    }


}
